import com.google.gdata.client.projecthosting.*;
import com.google.gdata.data.*;
import com.google.gdata.data.projecthosting.*;
import com.google.gdata.util.ResourceNotFoundException;
import com.google.gdata.util.ServiceForbiddenException;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.Timestamp;
import java.util.List;
import java.util.Vector;

 

/*@Sangeeta
 *Program to download Chrome browser comments database
 * 
 * */

public class comments_downloader_chrome {

	private String project = "chromium";
	
	private Connection conn = null;
    
	private String url = "jdbc:mysql://localhost:3306/";
    private String userName = "root"; 
    private String password = "123";
    
    /*private String url = "jdbc:mysql://localhost:3307/";
    private String userName = "sangeetal"; 
    private String password = "sangeetal";*/
    
    private String dbName = "apsec2014"; 
    private String driver = "com.mysql.jdbc.Driver";
   
    private String TABLE = "comments_chrome_browser";
    private ProjectHostingService myService = null;
	
	private void initdb(){
		 try {
		      Class.forName(driver).newInstance();
		      conn = DriverManager.getConnection(url+dbName,userName,password);
		  
		 } catch (Exception e) {
		      e.printStackTrace();
		 }
	}
	
	private void closedb(){ 
		 try {
		      conn.close();
		    } catch (Exception e) {
		      e.printStackTrace();
		    }
	} 
	
	private void insert(int issueID, String state, String status, Vector<String> comments)
	{ 
		try
		{
		  if(conn!=null)
		  {
		   Statement stmt = conn.createStatement();		    
		   String insertString = "";
		   if(comments.size()==0)
		     {
			    insertString = "insert into  "+ TABLE+ " values("+ issueID+","+0+",' ')";
			    stmt.executeUpdate(insertString);
			
		  }			
		   
		else
		 {  
			for(int i=0;i<comments.size();i++)
		      {
					String ith_comment = comments.get(i).replaceAll(",", " ");
					ith_comment = comments.get(i).replaceAll("\"", " ");
					ith_comment = comments.get(i).replaceAll("'", " ");
					
				    insertString = "insert into "+ TABLE+" values("+issueID+","+(i+1)+",'"+ith_comment+"')";
			       stmt.executeUpdate(insertString);
			
			  }
			  		  
		 }	 
	
	   stmt.close();
      }
		  
		}catch(Exception e) 
		{
			e.printStackTrace();
			
			
		}
		
		/*
		String insertString ="";
		if(closed!=null)
		{
		 insertString = "insert into " + TABLE + " VALUES (" + issueID + ",'" + state + "','" + status + "','" + 
		reported + "','" + closed + "','" + owner + "','" + title + "','" + description + "','" + area + "','" +
		type + "','" + pri + "','" + feature + "','" + secSeverity + "'," + security + "," + timediffhrs + "," + 
		regression + "," + performance + "," + cleanup + "," + polish + "," +  usability + "," + crash + "," +
		stars + "," + numcomments +",'"+label_str+ "','"+milestone+"',"+movedfrom_count+",'"+os+"','"+cr+"'"+")";
		}
		
		else
		{
			String zero_closed_date = "0000.00.00 00.00.00";
			 insertString = "insert into " + TABLE + " VALUES (" + issueID + ",'" + state + "','" + status + "','" + 
				reported + "','" + zero_closed_date + "','" + owner + "','" + title + "','" + description + "','" + area + "','" +
				type + "','" + pri + "','" + feature + "','" + secSeverity + "'," + security + "," + timediffhrs + "," + 
				regression + "," + performance + "," + cleanup + "," + polish + "," +  usability + "," + crash + "," +
				stars + "," + numcomments +",'"+label_str+ "','"+milestone+"',"+movedfrom_count+",'"+os+"','"+cr+"'"+")";
				
			
		}
		System.out.println(insertString); 
		try {
			
			if(conn!=null)
			{
			  Statement stmt = conn.createStatement();
	   		  stmt.executeUpdate(insertString);
			 stmt.close();
			}
			else
			{
				System.out.println("Chec user name");
				System.exit(0);
			}
			
		} catch(Exception e) {
			System.out.println(e);
			e.printStackTrace();
		}*/
	}
	

	
public void printAllIssueComments(String IssueId) {
		try{
			  URL feedUrl = new URL("https://code.google.com/feeds/issues/p/" + project + "/issues/" + IssueId + "/comments/full");
			  IssueCommentsFeed resultFeed = myService.getFeed(feedUrl, IssueCommentsFeed.class);

			  for (int i = 0; i < resultFeed.getEntries().size(); i++) {
			    IssueCommentsEntry entry = resultFeed.getEntries().get(i);
			 
			    TextContent textContent = (TextContent) entry.getContent();
			    if (textContent != null && textContent.getContent() != null) {
			      HtmlTextConstruct htmlConstruct = (HtmlTextConstruct) textContent.getContent();
			      System.out.println("\t" + htmlConstruct.getHtml());
			    }
			  }
			  System.out.println();
		}catch(Exception e){
			System.out.println(e);
		}
	}

  public Vector<String> getAllComments(String IssueId)
  {
	  Vector<String> comments = new Vector<String>();
	  int issue_count = 0;
	  try{
		  URL feedUrl = new URL("https://code.google.com/feeds/issues/p/" + project + "/issues/" + IssueId + "/comments/full");
		 
		  ///new
		  IssuesQuery myQuery = new IssuesQuery(feedUrl);
		  myQuery.setMaxResults(10000);
		  IssueCommentsFeed resultFeed = myService.getFeed(myQuery, IssueCommentsFeed.class);
		  
		  ///new
		  
		  
		 //@@NOT A COOMEN/ IssueCommentsFeed resultFeed = myService.getFeed(feedUrl, IssueCommentsFeed.class);
		  issue_count = resultFeed.getEntries().size();
		  
		   //Following will give all the issue comments
		  
		  for (int i = 0; i < resultFeed.getEntries().size(); i++)
		   {
			  
			  System.out.println("\n======================= i ="+(i+1)+"\n");
		    IssueCommentsEntry entry = resultFeed.getEntries().get(i);
		    
		    TextContent textContent = (TextContent) entry.getContent();
		    if (textContent != null && textContent.getContent() != null) {
		      HtmlTextConstruct htmlConstruct = (HtmlTextConstruct) textContent.getContent();
		      //System.out.println("\t" + htmlConstruct.getHtml());// Not a comment
		      comments.add(htmlConstruct.getHtml());
		    }//if
		    
		    System.out.println("\n=======================\n");
		  }
		  System.out.println();
		  
	}catch(Exception e){
		System.out.println(e);
	}
	
	return comments;
  }
	
	public int GetIssueComments_count(String IssueId) {
		int result = 0;
		try{
			  URL feedUrl = new URL("https://code.google.com/feeds/issues/p/" + project + "/issues/" + IssueId + "/comments/full");
			 
			  ///new
			  IssuesQuery myQuery = new IssuesQuery(feedUrl);
			  myQuery.setMaxResults(10000);
			  IssueCommentsFeed resultFeed = myService.getFeed(myQuery, IssueCommentsFeed.class);
			  
			  ///new
			  
			  
			 //@@NOT A COOMEN/ IssueCommentsFeed resultFeed = myService.getFeed(feedUrl, IssueCommentsFeed.class);
			  result = resultFeed.getEntries().size();
			  
			   //Following will give all the issue comments
			  
			  for (int i = 0; i < resultFeed.getEntries().size(); i++)
			   {
				  
				  System.out.println("\n======================= i ="+(i+1)+"\n");
			    IssueCommentsEntry entry = resultFeed.getEntries().get(i);
			    
			    TextContent textContent = (TextContent) entry.getContent();
			    if (textContent != null && textContent.getContent() != null) {
			      HtmlTextConstruct htmlConstruct = (HtmlTextConstruct) textContent.getContent();
			     // System.out.println("\t" + htmlConstruct.getHtml());// Not a comment
			    }//if
			    
			    System.out.println("\n=======================\n");
			  }
			  System.out.println();
			  
		}catch(Exception e){
			System.out.println(e);
		}
		return result;
	}
	

	
	public void extractInformation(ProjectHostingService service, String issueId)
	{
		try
		  { 
			URL feedUrl = new URL("https://code.google.com/feeds/issues/p/"+ project+"/issues/full/" + issueId);
			IssuesEntry entry = service.getEntry(feedUrl, IssuesEntry.class);
			
			System.out.println("-------------------------------------------------------------");
			Id id = entry.getIssueId();
			int issueID = id.getValue();
			List<Label> labels =  entry.getLabels();
			for(int i=0;i<labels.size();i++)
			{
				Label l = labels.get(i);
				l.getValue();
				//System.out.println("i="+labels.get(i));
			}
			//interupt();
			String state = entry.getState().getValue().name();
			String status ="";
			try{
			     status= entry.getStatus().getValue();
			}catch (Exception e)
			{System.out.println("Status Exception");
			}
			
			        System.out.println("*************************************************************");
		    		System.out.println("ISSUE ID : " + issueID);
		    		System.out.println("STATE : " + state);
		    		System.out.println("STATUS : " + status);
		    		Vector<String> comments  = new Vector<String>();
		    		comments = getAllComments(issueId);
		    		
		    			
		    		
		    		System.out.println("*************************************************************");
		    		insert(issueID, state, status, comments); 
		    	//}
		    //}
		}catch(ServiceForbiddenException e)
		{
			System.out.println("Not allowed");
		}
			
		catch(ResourceNotFoundException e)
		{
			System.out.println("Not allowed");
		}
		catch(Exception e){
			System.out.println(e);
			e.printStackTrace();
			System.exit(0);
		}
	}	
	public void process(){
		try{
			myService = new ProjectHostingService("Sample Application");
			//printAllIssues(myService, project);
			
			for(int i=7;i<=100;i++){
				extractInformation(myService, Integer.toString(i)); 
				//interupt();
			}
			
			//specificIssue(myService, "60055");
			//extractInformation(myService, "60055"); 
		}catch(Exception e){
			System.out.println(e);
			e.printStackTrace();
			
		}
	}
	
	public void interupt()
	{
		
		BufferedReader br =  new BufferedReader(new InputStreamReader(System.in));
		System.out.println("Intr");
		try {
			br.readLine();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

public static void main(String[] args){
		comments_downloader_chrome ite = new comments_downloader_chrome();
		ite.initdb();
		ite.process();
		ite.closedb();
	}
}

